package com.pureut.equipment.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.equipment.domain.DeviceParameter;
import com.pureut.equipment.domain.DeviceRecord;
import com.pureut.equipment.domain.dto.DeviceOperationDto;
import com.pureut.equipment.domain.dto.DeviceParameterDto;
import com.pureut.equipment.domain.dto.DeviceRecordDto;
import com.pureut.equipment.domain.dto.GetDeviceInfoDto;
import com.pureut.equipment.domain.vo.DeviceParameterVo;
import com.pureut.equipment.domain.vo.DeviceRecordVo;
import com.pureut.equipment.domain.vo.ReturnDeviceStatusVo;
import com.pureut.equipment.mapper.DeviceParameterMapper;
import com.pureut.equipment.mapper.DeviceRecordMapper;
import com.pureut.equipment.service.DeviceRecordService;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/2/13  11:22
 */

@Service
public class DeviceRecordServiceImpl extends ServiceImpl<DeviceRecordMapper, DeviceRecord> implements DeviceRecordService {

    /**
     * 设备台账信息
     */
    @Resource
    private DeviceRecordMapper deviceRecordMapper;

    /**
     * 编码生成配置
     */
    @Resource
    FeignService feignService;

    @Resource
    private DeviceParameterMapper deviceParameterMapper;


    /**
     * 设备台账
     *
     * @param deviceRecordVo
     * @return
     */
    @Override
    public List<DeviceRecordDto> getList(DeviceRecordVo deviceRecordVo) {
        List<DeviceRecordDto> deviceList = deviceRecordMapper.getDeviceList(deviceRecordVo);

        List<SysDictData> statusArray = DictUtils.getDictCache("device_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<SysDictData> typeArray = DictUtils.getDictCache("device_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (DeviceRecordDto deviceRecordDto : deviceList) {
            deviceRecordDto.setDeviceTypeDict(deviceRecordDto.getDeviceType());
            deviceRecordDto.setDeviceStatusDict(deviceRecordDto.getDeviceStatus());
            deviceRecordDto.setDeviceType(typeMap.get(deviceRecordDto.getDeviceType()));
            deviceRecordDto.setDeviceStatusDict(statusMap.get(deviceRecordDto.getDeviceStatus()));
        }


        return deviceList;
    }

    /**
     * 新增设备台账
     *
     * @param deviceRecordVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deviceAdd(DeviceRecordVo deviceRecordVo) throws Exception {
        DeviceRecord deviceRecord = new DeviceRecord();
        BeanUtils.copyProperties(deviceRecordVo, deviceRecord);
        deviceRecord.setDeptId(SecurityUtils.getDeptId());
        String authorityCoding = feignService.getAuthorityCoding("device:equipment:list");
        if (authorityCoding == null) {
            throw new GlobalException("该单据未进行配置，无法生成单据编码");
        }
        deviceRecord.setDeviceCode(authorityCoding);

        if ("1".equals(deviceRecord.getDeviceStatus())) {
            deviceRecord.setEquipmentOperationStatus(1);
        }

        int insertDevice = deviceRecordMapper.insertDevice(deviceRecord);

        //新增成功开始新增工艺参数
        if (insertDevice > 0) {
            List<DeviceParameterVo> list = deviceRecordVo.getList();
            List<DeviceParameter> parameterList = new ArrayList<>();

            if (list != null) {
                for (DeviceParameterVo DeviceParameterVo : list) {
                    DeviceParameter DeviceParameter = new DeviceParameter();
                    BeanUtils.copyProperties(DeviceParameterVo, DeviceParameter);
                    DeviceParameter.setDeviceCode(authorityCoding);
                    DeviceParameter.setDeviceAddedit(DeviceParameterVo.getDeviceAddedit());
                    DeviceParameter.setDeviceUnit(DeviceParameterVo.getDeviceUnit());
                    parameterList.add(DeviceParameter);

                }

                insertDevice = deviceParameterMapper.insertParameter(parameterList);
                if (insertDevice == 0) {
                    throw new GlobalException("新增失败");
                }
            }

        }
        return insertDevice;
    }

    /**
     * 设备台账修改
     *
     * @param deviceRecordVo
     * @return
     */
    @Override
    public int deviceEdit(DeviceRecordVo deviceRecordVo) {
        DeviceRecordDto deviceRecordDto = deviceRecordMapper.viewRecord(deviceRecordVo.getId());
        String deviceCode = deviceRecordDto.getDeviceCode();
        DeviceRecord deviceRecord = new DeviceRecord();
        BeanUtils.copyProperties(deviceRecordVo, deviceRecord);

        if ("2".equals(deviceRecord.getDeviceStatus())) {
            deviceRecord.setEquipmentOperationStatus(0);
        }

        int updateDevice = deviceRecordMapper.updateDevice(deviceRecord);
        //如果设备信息修改成功
        if (updateDevice > 0) {
            //删除设备明细信息
            int i = deviceParameterMapper.removeDeviceParameter(deviceCode);
            //添加设备明细信息
            List<DeviceParameterVo> list = deviceRecordVo.getList();
            List<DeviceParameter> DeviceParameterList = new ArrayList<>();
            for (DeviceParameterVo DeviceParameterVo : list) {
                DeviceParameter DeviceParameter = new DeviceParameter();
                BeanUtils.copyProperties(DeviceParameterVo, DeviceParameter);
                DeviceParameter.setDeviceCode(deviceCode);
                DeviceParameter.setDeviceAddedit(DeviceParameterVo.getDeviceAddedit());
                DeviceParameter.setDeviceUnit(DeviceParameterVo.getDeviceUnit());
                DeviceParameterList.add(DeviceParameter);
            }
            deviceParameterMapper.insertParameter(DeviceParameterList);
        }
        return updateDevice;
    }

    /**
     * 查看设备台账信息
     *
     * @param id
     * @return
     */
    @Override
    public DeviceRecordDto view(long id) {
        //查询设备信息
        DeviceRecordDto deviceRecordDto = deviceRecordMapper.viewRecord(id);
        List<SysDictData> statusArray = DictUtils.getDictCache("device_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<SysDictData> typeArray = DictUtils.getDictCache("device_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        deviceRecordDto.setDeviceType(deviceRecordDto.getDeviceType());
        deviceRecordDto.setDeviceStatus(deviceRecordDto.getDeviceStatus());
        deviceRecordDto.setDeviceTypeDict(typeMap.get(deviceRecordDto.getDeviceType()));
        deviceRecordDto.setDeviceStatusDict(statusMap.get(deviceRecordDto.getDeviceStatus()));

        //获取设备编码

        String deviceCode = deviceRecordDto.getDeviceCode();
        //根据设备编码查出工艺参数
        List<DeviceParameterDto> DeviceParameterDtoList = deviceParameterMapper.getDeviceParameter(deviceCode);
        deviceRecordDto.setList(DeviceParameterDtoList);
        return deviceRecordDto;
    }

    /**
     * 删除设备台账信息
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(String ids) {
        String[] DeviceIds = ids.split(",");

        int delete = 0;
        for (String deviceId : DeviceIds) {
            DeviceRecordDto deviceRecordDto = deviceRecordMapper.viewRecord(Long.parseLong(deviceId));
            String a = deviceRecordDto.getDeviceCode();
            delete = deviceParameterMapper.removeDeviceParameter(deviceRecordDto.getDeviceCode());
        }

        if (delete > 0) {
            deviceRecordMapper.removeByIds(DeviceIds);
        }

        return delete;
    }

    /**
     * 根据线别编码查询设备信息
     *
     * @param lineCode
     * @return
     */
    @Override
    public DeviceRecordDto getLine(String lineCode) {
        DeviceRecordDto deviceRecordDto = deviceRecordMapper.getLine(lineCode);
        List<SysDictData> statusArray = DictUtils.getDictCache("device_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<SysDictData> typeArray = DictUtils.getDictCache("device_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        deviceRecordDto.setDeviceTypeDict(deviceRecordDto.getDeviceType());
        deviceRecordDto.setDeviceStatusDict(deviceRecordDto.getDeviceStatus());
        deviceRecordDto.setDeviceType(typeMap.get(deviceRecordDto.getDeviceType()));
        deviceRecordDto.setDeviceStatus(statusMap.get(deviceRecordDto.getDeviceStatus()));
        return deviceRecordDto;
    }

    /**
     * 根据设备编码查出设备名称，设备类型，属性列表
     *
     * @param deviceCode
     * @return
     */
    @Override
    public GetDeviceInfoDto getDeviceInfo(String deviceCode) {
        GetDeviceInfoDto DeviceInfo = deviceRecordMapper.getDeviceInfo(deviceCode);
        List<SysDictData> typeArray = DictUtils.getDictCache("device_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        DeviceInfo.setDeviceType(typeMap.get(DeviceInfo.getDeviceType()));
        return DeviceInfo;
    }

    /**
     * 设备运行情况
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<DeviceOperationDto> getDeviceCondition(String lineCode) {
        List<DeviceOperationDto> deviceCondition = deviceRecordMapper.getDeviceCondition(lineCode);

        List<SysDictData> typeArray = DictUtils.getDictCache("equipment_operation_status");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (DeviceOperationDto deviceOperationDto : deviceCondition) {

            deviceOperationDto.setEquipmentOperationStatus(typeMap.get(deviceOperationDto.getEquipmentOperationStatus()));
        }
        return deviceCondition;
    }

    /**
     * 修改设备运行状态
     *
     * @param status
     * @return
     */
    @Override
    public boolean updateEquipmentOperationStatus(int status) {
        return deviceRecordMapper.updateEquipmentOperationStatus(status);
    }

    /**
     * 设备状态回传（fegin）
     *
     * @param returnDeviceStatusVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean returnDeviceStatus(ReturnDeviceStatusVo returnDeviceStatusVo) {
        List<String> deviceIdList = Arrays.asList(returnDeviceStatusVo.getDeviceIds().split(","));
        List<DeviceRecord> deviceRecords = deviceRecordMapper.selectDeviceByIds(deviceIdList);
        for (DeviceRecord entity : deviceRecords) {
            //出现维保的情况下后优先级为：维修>保养>点检>巡检
            if (returnDeviceStatusVo.getStatus() == 3) {
                entity.setEquipmentOperationStatus(3);
            } else if (entity.getEquipmentOperationStatus() != 3 && returnDeviceStatusVo.getStatus() == 2) {
                entity.setEquipmentOperationStatus(2);
            }else if(entity.getEquipmentOperationStatus() != 3 && returnDeviceStatusVo.getStatus() == 4){
                entity.setEquipmentOperationStatus(4);
            }else {
                entity.setEquipmentOperationStatus(5);
            }
        }
        return updateBatchById(deviceRecords);
    }


}
